<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Db;

/**
 * 原型打印变量
 * @param  object $arr 要打印的变量
 */
function p($arr)
{
    echo '<pre>';
    print_r($arr);
    echo '</pre>';
}

/**
 * json
 * @param  int     $status   业务状态码
 * @param  string  $message  返回信息
 * @param  array   $data     返回数据
 * @param  int     $httpCode http 状态码
 * @param  array   $header   http 头
 */
function j($status, $message, $data = [], $httpCode = 200, $header = ['Content-Type' => 'text/plain;charset=utf-8'])
{
    return json(['status' => $status, 'message' => $message, 'data' => $data], $httpCode);
}

/**
 * 简化 htmlspecialchars
 * @param  string $str 实体化的字符串
 */
function htmls($str)
{
    return htmlspecialchars($str);
}

/**
 * 随机字符串
 * @param  int $len 字符串长度
 */
function unid($len = 0)
{
    $str = md5(uniqid(microtime(true)).mt_rand());
    return $len ? substr($str, 0, $len) : $str;
}

/**
 * 盐加密密码
 * @param  string $pass 密码
 * @param  string $salt 盐字串
 */
function salt_pass($pass, $salt)
{
    return md5(md5($pass).$salt);
}

/**
 * 获取 session 作用域
 */
function session_prefix()
{
    return md5((request()->module() ?: 'addons').config('system.session_key'));
}

/**
 * 验证验证器
 * @param  array  $data  请求的数据
 * @param  string $scene 验证场景
 */
function validate_rule($data, $scene = '')
{
    $controller    = request()->controller();
    $validate_file = str_replace("\\", "/", \think\facade\Env::get('app_path')) . 'common/validate/' . $controller . '.php';
    if (file_exists($validate_file)) {
        $validate = validate(request()->controller());
        $scene    = $scene ?: ($validate->hasScene('add') ? 'add' : '');
        if ($validate->hasScene($scene)) {
            if (!$validate->scene($scene)->check($data)) {
                return $validate->getError();
            }
        }
    }
    return true;
}

/**
 * 递归重组多维数组
 * @param  array  $arr 数据数据
 * @param  int    $pid 父级 id
 */
function recursion_many_array($arr, $pid = 0)
{
    $data = [];
    foreach ($arr as $v) {
        if ($v['parent_id'] == $pid) {
            $v['child'] = recursion_many_array($arr, $v['id']);
            $data[]     = $v;
        }
    }
    return $data;
}

/**
 * 递归重组一维数组
 * @param  array   $arr   数组数据
 * @param  int     $pid   父级 id
 * @param  string  $html  html 标签
 * @param  int     $level 级别
 */
function recursion_one_array($arr, $pid = 0, $html = '&nbsp;&nbsp;&nbsp;&nbsp;', $level = 0)
{
    $data = [];
    foreach ($arr as $v) {
        if ($v['parent_id'] == $pid) {
            $v['level'] = $level + 1;
            $v['html']  = str_repeat($html, $level);
            $data[]     = $v;
            $data       = array_merge($data, recursion_one_array($arr, $v['id'], $html, $level + 1));
        }
    }
    return $data;
}

/**
 * 获取数据表字段
 * @param  string $table 数据表名称
 * @return array
 */
function get_fields($table)
{
    $table  = parse_model_name($table);
    $prefix = config('database.prefix');
    $data   = Db::query("SELECT COLUMN_NAME,column_comment FROM INFORMATION_SCHEMA.Columns WHERE table_name='{$prefix}{$table}'");
    $fields = [];
    foreach ($data as $v) {
        $fields[] = $v['COLUMN_NAME'];
    }
    return $fields;
}

/**
 * 解析模型名称
 * @param  string $modelName 模型名称
 * @return array
 */
function parse_model_name($modelName)
{
    $table = ltrim(preg_replace('/([A-Z])/', '_${1}', $modelName), '_');
    return strtolower($table);
}

/**
 * 解析数据表名称
 * @param  string $tableName 数据表名称
 * @return array
 */
function parse_table_name($tableName)
{
    $temp  = explode('_', $tableName);
    $model = '';
    foreach ($temp as $v) {
        $model .= ucfirst($v);
    }
    return $model;
}

/**
 * 转换尺寸到友好的单位
 * @param  float $size 原始尺寸（单位：kb）
 * @return float       转换后的尺寸
 */
function transfer_size($size)
{
    static $index = 0;
    $unit = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB', 'BB'];
    if ($size >= 1024) {
        $size = round($size/1024, 2);
        if ($index < count($unit)) {
            $index++;
            return transfer_size($size);
        }
    }
    return $size.$unit[$index];
}

/**
 * 获取附件 html
 * @param  string $attach_id 附件id
 * @param  string $name      列名
 * @param  string $type      附件类型，pic: 图片; file: 文件;
 */
function attach_html($attach_id, $name, $type = 'pic')
{
    $str  = '';
    if ($attach_id) {
        if (is_numeric($attach_id)) {
            $attach = attach($attach_id);
            $str .= '<li><img src="'.$attach['attach_uri'].'" alt="" /><a class="u-item"><i class="icon icon-remove"></i></a><input type="hidden" name="'.$name.'" value="'.$attach_id.'" /></li>';
        } elseif (is_array($attach_id)) {
            foreach ($attach_id as $v) {
                $attach = attach($v['value']);
                if ($type == 'pics') {
                    $str .= '<li><img src="'.$attach['attach_uri'].'" alt="" /><div class="m-textarea"><textarea name="'.$name.'[desc][]">'.$v['desc'].'</textarea></div><a class="u-item"><i class="icon icon-remove"></i></a><input type="hidden" name="'.$name.'[value][]" value="'.$v['value'].'" /></li>';
                } elseif ($type == 'file') {
                    $str .= '<li><i class="icon-paper-clip"></i><input type="text" name="'.$name.'[name][]" value="'.($v['name'] ?: $attach['title']).'" /><a data-md5-file="'.$attach['md5_file'].'" data-id="'.$v['value'].'" class="u-download">下载</a><a class="u-item" data-id="'.$v['value'].'">删除</a><input type="hidden" name="'.$name.'[value][]" value="'.$v['value'].'" /></li>';
                }
            }
        }
    }
    return $str;
}

/**
 * 获取附件 html
 * @param  string $attach_id 附件id
 * @param  string $name      列名
 * @param  string $type      附件类型，pic: 图片; file: 文件;
 */
function s_attach_html($attach_id, $name, $type = 'pic')
{
    $str  = '';
    if(!$attach_id){
        return "";
    }
    $attach_id=explode(',',$attach_id);
    if ($attach_id) {
        foreach ($attach_id as $v) {
            $attach = attach($v);
            if ($type == 'pics') {
                $str .= '<li><img src="'.$attach['attach_uri'].'" alt="" /><div class="m-textarea"></div><a class="u-item"><i class="icon icon-remove"></i></a><input type="hidden" name="'.$name.'[value][]" value="'.$v.'" /></li>';
            } elseif ($type == 'file') {
                $str .= '<li><i class="icon-paper-clip"></i><input type="text" name="'.$name.'[name][]" value="'.($v['name'] ?: $attach['title']).'" /><a data-md5-file="'.$attach['md5_file'].'" data-id="'.$v.'" class="u-download">下载</a><a class="u-item" data-id="'.$v['value'].'">删除</a><input type="hidden" name="'.$name.'[value][]" value="'.$v['value'].'" /></li>';
            }
        }
    }

    return $str;
}

/**
 * 获取附件信息
 * @param  int $attach_id 附件 id
 */
function attach($attach_id)
{
    return Db::name('attaches')->field('id,module,userid,title,attach_uri,md5_file,type')->where('id', $attach_id)->find();
}


/**
 * 获取附件地址
 * @param  int $attach_id 附件 id
 */
function attach_uri($attach_id)
{
    $att = attach($attach_id);
    if ($att['type'] == 0) {
        $result = config('system.attach_uri_prefix').ltrim($att['attach_uri'], '/');
    }else{
        $result = $att['attach_uri'];
    }

    Log::write($result,'notice');
    return $result;
}
/**
 * 验证变量规则
 * @param  string $regex 匹配的规则
 * @param  string $value 验证的变量
 */
function valid_var($regex, $value)
{
    return preg_match($regex, $value);
}

/**
 * 获取内容信息
 * @param  string|array $params 查询条件
 * @return array
 */
function query_contents($params = '')
{
    $result = parse_params('contents', $params);
    return \app\common\service\Contents::contents($result['where'], $result['order'], $result['limit']);
}

/**
 * 解析查询条件参数
 * @param  string       $tblName 数据表名称
 * @param  string|array $params  查询条件
 * @return array
 */
function parse_params($tblName, $params)
{
    $where    = [];
    $order    = '';
    $limit    = '';
    $isPost   = 0;
    $postNums = 10;
    if (is_array($params) && !empty($params)) {
        // 数组参数
        $order  = isset($params['orderby']) ? $params['orderby'] : '';
        $page   = isset($params['page']) ? (int)$params['page'] : 1;
        $limit  = isset($params['limit']) ? (int)$params['limit'] : (int)config('params.default.home_list_limit');
        $offset = isset($params['offset']) ? (int)$params['offset'] : ($page - 1) * $limit;
        $limit  = $offset . ',' . $limit;

        if (isset($params['orderby'])) unset($params['orderby']);
        if (isset($params['page'])) unset($params['page']);
        if (isset($params['offset'])) unset($params['offset']);
        if (isset($params['limit'])) unset($params['limit']);

        $where = $params;
    } elseif (is_string($params) && $params) {
        // 字符串参数
        $arr = explode('&', $params);
        foreach ($arr as $v) {
            $temp = explode('=', $v);
            if ($temp[0] == 'orderby') {
                $order = $temp[1];
            } elseif ($temp[0] == 'offset') {
                $limit .= $temp[1] . ',';
            } elseif ($temp[0] == 'limit') {
                $limit .= $temp[1];
            } elseif ($temp[0] == 'ispost') {
                $isPost = $temp[1];
            } elseif ($temp[0] == 'postnums') {
                $postNums = $temp[1];
            } else {
                $where = array_merge($where, [$temp[0] => $temp[1]]);
            }
        }
    } elseif (is_numeric($params) && $params) {
        // 数值参数，直接以主键为条件
        $where = [
            'id' => (int)$params,
        ];
    }

    if (!$where) {
        // 无参数，直接以当前 url 为条件
        $url = input('param.url/s', '');
        $num = input('param.num/d', 0);
        if ($url) {
            $url  .= $num ? '-'.$num : '';
            $where = [
                'url' => $url,
            ];
        }
    }

    if (!isset($where['id']) && !isset($where['url'])) {
        $fields = get_fields($tblName);
        $zWhere = [];
        foreach ($where as $k => $v) {
            if (in_array($k, $fields)) {
                if (is_array($v)) {
                    if (count($v) == 1) {
                        $zWhere[] = [$k, 'in', $v[0]];
                    } else {
                        $zWhere[] = [$k, $v[0], $v[1]];
                    }
                } else {
                    $zWhere[] = [$k, 'eq', $v];
                }
            }
        }
    } elseif (isset($where['id'])) {
        $zWhere = [
            'id' => $where['id'],
        ];
    } elseif (isset($where['url'])) {
        $zWhere = [
            'url' => $where['url'],
        ];
    }

    return [
        'where'    => $zWhere,
        'order'    => $order,
        'limit'    => $limit,
        'isPost'   => $isPost,
        'postNums' => $postNums,
    ];
}

/**
 * 获取数据库中的所有数据表
 */
function get_tables()
{
    $rows = Db::query("SHOW TABLES");
    $data = [];
    foreach ($rows as $row) {
        $data[] = $row['Tables_in_cms'];
    }
    return $data;
}

/**
 * 编辑数据表
 * @param  string $data 数据表信息
 */
function edit_table($data)
{
    if ($data['origin_name']) {
        // 编辑数据表
        if ($data['origin_name'] != $data['tbname']) {
            Db::query("ALTER TABLE `".config('database.prefix')."{$data['origin_name']}` RENAME TO `".config('database.prefix')."{$data['tbname']}`");
        }
        Db::query("ALTER TABLE `".config('database.prefix')."{$data['tbname']}` COMMENT '".$data['name']."'");
    } else {
        // 添加数据表
        Db::query("CREATE TABLE IF NOT exists `".config('database.prefix')."{$data['tbname']}`("
            ."`id` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键 id',"
            ."`column_id` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '栏目 id',"
            ."PRIMARY KEY (`id`),"
            ."KEY `column_id` (`column_id`)"
            .")ENGINE=MyISAM DEFAULT CHARSET=UTF8 COMMENT '".$data['name']."'");
    }
}

/**
 * 获取所有父级 id
 * @param  string $model 模型
 * @param  int    $id    当前菜单 id
 */
function get_super_ids($model, $id)
{
    $data     = [];
    $parentId = $model::where('id', $id)->value('parent_id');
    if ($parentId) {
        $data[] = $parentId;
        $data   = array_merge($data, get_super_ids($model, $parentId));
    }
    return $data;
}

/**
 * 获取所有子级 id
 * @param  string $model 模型
 * @param  int    $id    当前菜单 id
 */
function get_sub_ids($model, $id)
{
    $ids  = $model::where('parent_id', $id)->column('id');
    $data = [];
    if (count($ids)) {
        foreach ($ids as $v) {
            $data[] = $v;
            $data   = array_merge($data, get_sub_ids($model, $v));
        }
    }
    return $data;
}

/**
 * base64_encode
 * @param  string $data 转码的数据
 */
function base64url_encode($data)
{
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

/**
 * base64_decode
 * @param  string $data 解码的数据
 */
function base64url_decode($data)
{
    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}

/**
 * 下载文件
 * @param  string $fileurl  文件地址
 * @param  string $filename 文件名称
 */
function download_file($fileurl, $filename)
{
    header("Content-Description: File Transfer");
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment;filename=".$filename);
    header("Content-Transfer-Encoding: binary");
    header("Expires: 0");
    header("Cache-Control: must-revalidate");
    header("Pragma: public");
    header("Content-Length: ". filesize($fileurl));
    ob_clean();
    flush();
    readfile($fileurl);
    exit();
}

/**
 * 生成栏目树
 * @param  array  $arr 栏目信息
 * @param  int    $pid 父级栏目 id
 */
function generate_tree_html($arr, $pid = 0)
{
    $html = '';
    if ($arr !== false) {
        $i = 0;
        foreach ($arr as $v) {
            if ($v['parent_id'] == $pid) {
                if ($v['is_last']) {
                    $html .= '<li class="m-file"><a href="'.url('contents/index', ['column_id' => $v['id']]).'" title="'.$v['id'].'" target="main"><i class="ico-columns-tree ico-tree-file"></i>'.$v['name'].'</a></li>';
                } else {
                    $html .= '<li class="m-folder"><a href="javascript:;" class="u-cate" title="'.$v['id'].'"><i class="ico-columns-tree icon-tree-control ico-tree-plus"></i><i class="ico-columns-tree ico-folder ico-tree-folder-close"></i><em>'.$v['name'].'</em></a><ul>'.generate_tree_html($arr, $v['id']).'</ul></li>';
                    $i++;
                }
            }
        }
    }
    return $html;
}

/**
 * 排序
 * @param  array $a 要排序的数组
 * @param  array $b 要排序的数组
 */
function cmp_func($a, $b) {
    global $order;
    if ($a['is_dir'] && !$b['is_dir']) {
        return -1;
    } else if (!$a['is_dir'] && $b['is_dir']) {
        return 1;
    } else {
        if ($order == 'size') {
            if ($a['filesize'] > $b['filesize']) {
                return 1;
            } else if ($a['filesize'] < $b['filesize']) {
                return -1;
            } else {
                return 0;
            }
        } else if ($order == 'type') {
            return strcmp($a['filetype'], $b['filetype']);
        } else {
            return strcmp($b['filename'], $a['filename']);
        }
    }
}

/**
 * curl 请求
 * @param string $url  请求地址
 * @param array  $data 请求的数据
 */
function curl_request($url, $data = null)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    if(!empty($data)){
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}
function getimg($id){
    $url=db('attaches')->where('id',$id)->find();
    return 'http://'.$_SERVER['SERVER_NAME'].$url['attach_uri'];
}


/*解析base64图片----微信头像*/
function imgSave($url){

    $header = array(
        'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
        'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
        'Accept-Encoding: gzip, deflate',);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

    $data = curl_exec($curl);
    $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    // p($code);die;
    curl_close($curl);
    $imgBase64Code='';
    if ($code == 200) {//把URL格式的图片转成base64_encode格式的！
        $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
    }


    if(empty($imgBase64Code)){
        return "";
    }else{
        $img_content=$imgBase64Code;//图片内容
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result))
        {
            $strDate    = date('Ymd');
            $a = "/static/uploads/api/image/upload/".$strDate."/".md5(uniqid()).'.jpg';

            $new_file = $_SERVER["DOCUMENT_ROOT"].$a;

            $strSaveFileDir  = dirname($new_file);
            if (!file_exists($strSaveFileDir)) {
                mkdir($strSaveFileDir, 0777, true);
            }
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content))) && file_exists($new_file)) {
                return $a;
            }else{
                return "";
            }

        }
    }
}
